package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Ingredients;
import com.etoak.mapper.DictMapper;
import com.etoak.mapper.IngredientsMapper;
import com.etoak.service.IngredientsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.CustomSQLExceptionTranslatorRegistrar;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author et2403
 * @since 2024-08-13
 */
@Service
public class IngredientsServiceImpl extends ServiceImpl<IngredientsMapper, Ingredients> implements IngredientsService {


    @Override
    public boolean addIngredients(Ingredients ingredients) {
        /* 校验食材名称 */
        Ingredients savedIngredients = getByName(ingredients.getName());
        if (ObjectUtils.isNotEmpty(savedIngredients)) {
            throw new CustomException("食材名称重复!");
        }

        ingredients.setCreateTime(DateUtil.now());

        return save(ingredients);
    }

    @Override
    public PageVO getList(Integer pageNum, Integer pageSize, Ingredients ingredients) {
        PageHelper.startPage(pageNum, pageSize);
        List<Ingredients> ingredientsList = baseMapper.getList(ingredients);
        PageInfo<Ingredients> pageInfo = new PageInfo<>(ingredientsList);
        return new PageVO(pageNum, pageSize, ingredientsList, pageInfo.getTotal());
    }

    @Override
    public boolean updateIngredients(int id, Ingredients ingredients) {
        /* 验证id */
        if (ObjectUtils.isEmpty(this.getById(id))) {
            throw new CustomException("食材不存在!");
        }
        /* 校验食材名称 */
        String ingredientsName = ingredients.getName();
        if (StringUtils.isNotEmpty(ingredientsName)) {
            Ingredients savedIngredients = this.getByName(ingredientsName);
            // 根据名称查到了食材，但此时他们的id不一致（此时，客户端想将名称修改为其他食材名称，直接返回）
            if (ObjectUtils.isNotEmpty(savedIngredients) && !savedIngredients.getId().equals(id)) {
                throw new CustomException("食材名称重复!");
            }
        }

        ingredients.setId(id);
        ingredients.setUpdateTime(DateUtil.now());

        return updateById(ingredients);
    }

    @Override
    public boolean deleteById(int id) {
        if (ObjectUtils.isEmpty(this.getById(id))) {
            throw new CustomException("食材不存在!");
        }

        // TODO 判断食材有没有被菜品使用

        return this.removeById(id);
    }

    private Ingredients getByName(String name) {
        return lambdaQuery().eq(Ingredients::getName, name).one();
    }
}
